package DB

import (
	"database/sql"
	"fmt"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

const (
	HOST     = "10.252.0.62"
	NAME     = "root"
	PWD      = "moqikaka3306"
	PORT     = "3306"
	DATABASE = "yangjie"
	CHARSET  = "utf8"
)

var dBA *dBManager

type dBManager struct {
	DB *sql.DB
}

func init() {
	DBA := NewDBManager()
	DBA.InitDB()
}

func NewDBManager() *dBManager {
	manager := &dBManager{
		DB: nil,
	}
	dBA = manager
	return dBA
}

func GetDBManager() *dBManager {
	return dBA
}

func (DBA *dBManager) InitDB() {

	//构建连接："用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
	path := strings.Join([]string{NAME, ":", PWD, "@tcp(", HOST, ":", PORT, ")/", DATABASE, "?charset=", CHARSET}, "")
	//打开数据库,前者是驱动名，所以要导入： _ "github.com/go-sql-driver/mysql"
	DBA.DB, _ = sql.Open("mysql", path)
	//设置数据库最大连接数
	DBA.DB.SetConnMaxLifetime(100)
	//设置上数据库最大闲置连接数
	DBA.DB.SetMaxIdleConns(10)
	//验证连接
	if err := DBA.DB.Ping(); err != nil {
		fmt.Println("open database fail")
		return
	}
	fmt.Println("connnect success")
}

func (DBA *dBManager) Query(sql string) (*sql.Rows, error) {
	return DBA.DB.Query(sql)
}

func (DBA *dBManager) Update(sql string) (sql.Result, error) {
	return DBA.DB.Exec(sql)
}
